package model

import "mytest/database"

// 菜单
type SystemMenu struct {
	Id        int    `gorm:"column:id" json:"id"`
	CreatedAt string `gorm:"column:created_at" json:"created_at" `
	UpdatedAt string `gorm:"column:updated_at" json:"updated_at" `
	DeletedAt string `gorm:"column:deleted_at" json:"deleted_at" `
	Pid       int    `gorm:"column:pid" json:"pid"`
	Title     string `gorm:"column:title" json:"title"`
	Icon      string `gorm:"column:icon" json:"icon"`
	Href      string `gorm:"column:href" json:"href"`
	Sort      string `gorm:"column:sort" json:"sort"`
	Target    string `gorm:"column:target" json:"target"`
	Remark    string `gorm:"column:remark" json:"remark"`
	Status    int    `gorm:"column:status" json:"status"`
}

// 菜单结构体
type MenuTreeList struct {
	Id     int             `gorm:"column:id" json:"id"`
	Pid    int             `gorm:"column:pid" json:"pid"`
	Title  string          `gorm:"column:title" json:"title"`
	Icon   string          `gorm:"column:icon" json:"icon"`
	Href   string          `gorm:"column:href" json:"href"`
	Target string          `gorm:"column:target" json:"target"`
	Remark string          `gorm:"column:remark" json:"remark"`
	Child  []*MenuTreeList `gorm:"column:child" json:"child"`
}

// 初始化结构体
type SystemInit struct {
	HomeInfo struct {
		Title string `json:"title"`
		Href  string `json:"href"`
	} `json:"homeInfo"`
	LogoInfo struct {
		Title string `json:"title"`
		Image string `json:"image"`
	} `json:"logoInfo"`
	MenuInfo []*MenuTreeList `json:"menuInfo"`
}

// 获取初始化数据
func (m SystemMenu) GetSystemInit() (SystemInit, error) {
	var systemInit SystemInit

	// 首页
	systemInit.HomeInfo.Title = "首页"
	systemInit.HomeInfo.Href = "welcome-1.html?t=1"

	// logo
	systemInit.LogoInfo.Title = "LAYUI MINI"
	systemInit.LogoInfo.Image = "/static/images/logo.png"

	menuInfo, err := m.GetMenuList()
	if err != nil {
		return systemInit, err
	}
	// 菜单
	systemInit.MenuInfo = menuInfo

	return systemInit, nil
}

// 获取菜单列表
func (m SystemMenu) GetMenuList() ([]*MenuTreeList, error) {
	var menuList []SystemMenu
	err := database.DB.Where("status = ?", 1).Order("sort desc").Find(&menuList).Error
	if err != nil {
		return nil, err
	}
	return m.buildMenuChild(0, menuList), nil
}

//递归获取子菜单
func (m SystemMenu) buildMenuChild(pid int, menuList []SystemMenu) []*MenuTreeList {
	var treeList []*MenuTreeList
	for _, v := range menuList {
		if pid == v.Pid {
			node := &MenuTreeList{
				Id:     v.Id,
				Title:  v.Title,
				Icon:   v.Icon,
				Href:   v.Href,
				Target: v.Target,
				Pid:    v.Pid,
			}
			child := v.buildMenuChild(v.Id, menuList)
			if len(child) != 0 {
				node.Child = child
			}
			// todo 后续此处加上用户的权限判断
			treeList = append(treeList, node)
		}
	}
	return treeList
}
